'use strict';


const fs = require('fs');
const path = require('path');
const router = require('koa-router')();


function searchControllers() {

    let files = fs.readdirSync(__dirname);

    let filterFile = files.filter(fileName => {
        return fileName.endsWith('.js') && fileName !== 'index.js';
    });

    return filterFile;
}


function registerRouter(file) {

    file.forEach(item => {

        let fullPath = path.join(__dirname, item);

        let routerObj = require(fullPath);

        for (let item in routerObj) {

            let type = routerObj[item][0];

            let fn = routerObj[item][1];

            if (type === 'get') {

                router.get(item, fn);
            } else if (type === 'post') {

                router.post(item, fn);
            } else if (type === 'put') {

                router.put(item, fn);
            } else if (type === 'delete') {

                router.delete(item, fn);
            } else {

                console.log(`请求类型有误！`);
            }
        }
    });
}


module.exports = function () {

    let file = searchControllers();

    registerRouter(file);

    return router.routes();
}